import { t } from 'i18next'
import { useState } from 'react'
import { Button, RangePicker, Space, InputNumber } from '@kedacom/react-next'
import { StyledWrap } from './style'
import dayjs from '@/plugins/dayjs'
import Logger from '@/plugins/log'
import Alert from '@/components/Alert'
import { saveAs } from '@/utils'

function Log() {
	const [timeVal, setTimeVal] = useState<[string | undefined, string | undefined]>(['', ''])
	const [startId, setStartId] = useState('')
	const [endId, setEndId] = useState('')
	const handleClear = () => {
		Alert(t('确定要清空所有日志'), () => {
			Logger.clear()
			t('清空成功')
		})
	}

	const getAllLog = () => {
		Logger.readAll().then(function (res: any) {
			var content = JSON.stringify(res)
			var blob = new Blob([content], { type: 'text/plain;charset=utf-8' })
			saveAs(blob, dayjs().format('YYYY/MM/DD/hh/mm') + '.json')
		})
	}
	const getLogByTime = () => {
		Logger.readByDate(timeVal[0] ?? '', timeVal[1] ?? '').then(function (res: any) {
			var content = JSON.stringify(res)
			var blob = new Blob([content], { type: 'text/plain;charset=utf-8' })
			saveAs(blob, dayjs().format('YYYY/MM/DD/hh/mm') + '.json')
		})
	}
	const getLogById = () => {
		Logger.readIdRange(Number(startId), Number(endId)).then(function (res: any) {
			var content = JSON.stringify(res)
			var blob = new Blob([content], { type: 'text/plain;charset=utf-8' })
			saveAs(blob, dayjs().format('YYYY/MM/DD/hh/mm') + '.json')
		})
	}
	return (
		<StyledWrap>
			<h3 className="title">{t('日志信息')}</h3>
			<Space>
				<Button onClick={handleClear}>{t('清空日志')}</Button>
				<Button onClick={getAllLog}>{t('获取所有日志')}</Button>
			</Space>
			<div className="time-picker">
				<span className="label">{t('根据日期')}</span>
				<RangePicker
					picker="datetime"
					format="YYYY/MM/DD HH:mm:ss"
					timeFormat="HH:mm:ss"
					className="start-time"
					value={timeVal}
					onChange={(e, val) => {
						setTimeVal(val)
					}}
					i18n={{
						confirm: t('确认'),
						year: t('年'),
						month: [
							t('一月'),
							t('二月'),
							t('三月'),
							t('四月'),
							t('五月'),
							t('六月'),
							t('七月'),
							t('八月'),
							t('九月'),
							t('十月'),
							t('十一月'),
							t('十二月'),
						],
						week: [t('日'), t('一'), t('二'), t('三'), t('四'), t('五'), t('六')],
					}}
				/>
				<Button className="btn" onClick={getLogByTime}>
					{t('保存')}
				</Button>
			</div>
			<div className="id-picker">
				<span className="label">{t('根据id')}</span>
				<InputNumber className="start-id" width={148} value={startId} onChange={(e, val) => setStartId(val)} />
				~
				<InputNumber className="end-id" width={148} value={endId} onChange={(e, val) => setEndId(val)} />
				<Button className="btn" onClick={getLogById}>
					{t('保存')}
				</Button>
			</div>
		</StyledWrap>
	)
}

export default Log
